from django.db import models
from hippo_api.utils.models import BaseModel
# from user.models import Users
from hippo_api.libs import SSH

from conf_center.models import Evrironment


# 全局密钥和共钥，所有用户都使用这个一对
class PkeyModel(BaseModel):
    key = models.CharField(max_length=50, unique=True)  # ssh私钥
    value = models.TextField()
    desc = models.CharField(max_length=255, null=True)  # 描述

    def __repr__(self):
        return '<Pkey %r>' % self.key


class HostCategory(BaseModel):
    name = models.CharField(max_length=32, verbose_name='主机类别')

    def __str__(self):
        return self.name

# 主机表
class Host(BaseModel):
    # 外建类别，更具有扩展性
    category = models.ForeignKey('HostCategory',on_delete=models.CASCADE, verbose_name='主机类别', related_name='hc', null=True, blank=True)

    hostname = models.CharField(max_length=50,verbose_name='主机名称')
    ip_addr = models.CharField(blank=True, null=True,max_length=50,verbose_name='连接地址')
    port = models.IntegerField(verbose_name='端口')
    username = models.CharField(max_length=50,verbose_name='登录用户')
    desc = models.CharField(max_length=255, null=True,verbose_name='描述')
    # 关联环境
    evrironments = models.ForeignKey(Evrironment, on_delete=models.CASCADE, default=1, verbose_name='测试环境')  # 默认1是测试环境

    # users = models.ManyToManyField(Users)
    def __str__(self):
        return self.hostname + ':' + self.ip_addr

    def get_ssh(self, pkey=None):
        # pkey = pkey or self.private_key
        return SSH(self.ip_addr, self.port, self.username, pkey)

